package com.teichmann.core.targets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.Tag;
import org.htmlparser.lexer.Lexer;
import org.htmlparser.nodes.TextNode;
import org.htmlparser.tags.TableColumn;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.htmlparser.visitors.NodeVisitor;

import com.teichmann.bo.Car;
import com.teichmann.bo.Seller;
import com.teichmann.core.Page;
import com.teichmann.core.annotations.Delimiter;
import com.teichmann.core.annotations.Url;
import com.teichmann.core.util.ConnectionUtils;

@Url(value = "http://www.autobellomultimarcas.com.br/site/veiculos.php")
@Delimiter(tag = "tr", attribute="onclick", value="abrir")
	public class AutoBello implements Page {
	
	ArrayList<Car> cars = new ArrayList<Car>();

	public ArrayList<Car> performSearch() throws IOException {

		// Read the response body.
		String responseBody =  ConnectionUtils.get(this.getClass().getAnnotation(Url.class).value());
		Parser parser = new Parser(new Lexer(responseBody));
		try {
			parser.visitAllNodesWith(visitor);
		} catch (ParserException e) {
			e.printStackTrace();
		}

		return cars;

	}

	/**
	 * @param line
	 * @return
	 * 
	 * Default line for Autobello's site is
	 * <tr class="txt" style="cursor: pointer;" onclick="javascript: abrirVeiculo('449');">
	 * <td class="txt" height="20">AUDI</td>
	 * <td class="txt">A6 2.8</td>
	 * <td class="txt">1995</td>
	 * <td class="txt">1995</td>
	 * <td class="txt">BZM0202</td>
	 * <td class="txt">VERMELHA</td>
	 * <td class="txt">22.500,00</td>
	 * <td class="txt"><img src="../imagens/sistema/maquina.gif"></td>
	 * </tr>
	 * 
	 */
	public Car extractInformation(Tag line){
		Car car = new Car();
		int count = 0;
		try {
		
			String url = String.copyValueOf(line.getAttribute("onClick").toCharArray(),line.getAttribute("onClick").indexOf("'"),(line.getAttribute("onClick").lastIndexOf("'")-line.getAttribute("onClick").indexOf("'"))); 
			car.setUrl("http://www.autobellomultimarcas.com.br/site/veiculos-visualizar.php?codveiculo="+url);

			NodeList details = line.getChildren();
			details = details.extractAllNodesThatMatch(new NodeFilter(){
				public boolean accept(Node arg0) {
					if (arg0 instanceof TableColumn) {
						return true;
						
					}
					
					return false;
				}
				
			});
			
			
			Pattern intOnly = Pattern.compile("\\d*");

			car.setMontadora(((TextNode)details.elementAt(count++).getChildren().elementAt(0)).getText());
			car.setModelo(((TextNode)details.elementAt(count++).getChildren().elementAt(0)).getText());

			//ano fabricacao
			String anoFabricacao =  ((TextNode)details.elementAt(count++).getChildren().elementAt(0)).getText();
			Matcher matcher = intOnly.matcher(anoFabricacao);
			if (matcher.find()){
				car.setAnoFabricacao(new Integer(matcher.group()));
			}
			else{
				car.setAnoFabricacao(new Integer(anoFabricacao));
			}

			// ano modelo
			String anoModelo =  ((TextNode)details.elementAt(count++).getChildren().elementAt(0)).getText();
			matcher = intOnly.matcher(anoModelo);
			if (matcher.find()){
				car.setAnoModelo(new Integer(matcher.group()));
			}
			else{
				car.setAnoModelo(new Integer(anoModelo));
			}
			
			car.setPlaca(((TextNode)details.elementAt(count++).getChildren().elementAt(0)).getText());
			car.setCor(((TextNode)details.elementAt(count++).getChildren().elementAt(0)).getText());
			car.setValor(((TextNode)details.elementAt(count++).getChildren().elementAt(0)).getText());
			car.setRevenda(new Seller(this.getClass().getName()));

		} catch (Exception e) {
			e.printStackTrace();
		}

		return car;

	}

	NodeVisitor visitor = new NodeVisitor() {

		@Override
		public void visitTag(Tag tag) {
			String name = tag.getTagName();
			if ("tr".equalsIgnoreCase(name)
					&& (tag.getAttribute("onclick") != null && tag
							.getAttribute("onclick").contains("abrir"))) {
				cars.add(extractInformation(tag));
			}
		}
	};

}
